<template>
  <div></div>
</template>

<style scoped>

  .g2-guide-html {
    display: inline-block;
    vertical-align: middle;
    text-align: center;
    font-size: 14px;
    color: #999;

    display: flex;
    align-items: center;
  }

  .g2-guide-html .value {
    font-size: 20px;
    /*color: #448CE9 !important;*/
    font-weight: bold;
  }

  .g2-guide-html .nodata {
    font-size: 16px;
    /*color: #448CE9 !important;*/
    /*font-weight: bold;*/
  }

</style>

<script>
  //import { chart } from '@antv/g2'

  export default {
    name: "chart",
    data() {
      chart : null;
      return {

      }
    },
    mounted: function () {
      let chart_type = this.types;
      if (chart_type === 'singleLinecharts') {
        this.singleLineChart()
      } else if (chart_type === 'singleLineWithAxischarts') {
        this.singleLineWithAxisChart()
      } else if (chart_type === 'doubleLinecharts') {
        this.doubleLineChart()
      } else if (chart_type === 'doubleLinewithrigntaxis') {
        this.doubleLinewithrigntaxis();
      } else if (chart_type === 'barcharts') {
        this.barChart()
      } else if (chart_type === 'groupBarcharts') {
        this.groupChart()
      } else if (chart_type === 'groupBarChart') {
        this.groupBarChart();
      } else if (chart_type === 'areacharts') {
        this.areaChart()
      } else if (chart_type === 'ringcharts') {
        this.ringChart()
      } else if (chart_type === 'dashboardcharts') {
        this.dashboardchart()
      } else if (chart_type === 'stackedBarChart') {
        this.stackedBarChart()
      }
    },
    props: ['types', 'ids', 'datas', 'widths', 'heights',
      'totals', 'color', 'max', 'min', 'level',
      'offset', 'lineWidth', 'legend', 'noLeg', 'totalStyle', 'padding',
      'lineAlias'],
    watch: {
      datas: {
        handler(newValue, oldValue) {
          if (this.types === 'dashboardcharts') {
            this.chart.clear();
            this.dashboardchart()
          } else if (this.types === 'stackedBarChart') {
            this.chart.clear();
            this.stackedBarChart()
          } else if (this.types === 'ringcharts') {
            this.chart.clear();
            this.ringChart()
          } else if (this.types === 'doubleLinewithrigntaxis') {
            this.doubleLinewithrigntaxis();
          }else {
            this.reload(newValue);
          }
        },
        deep: true
      }
    },
    methods: {
      reload: function (data) {
        this.chart.source(data);
        this.chart.render();
      },
      clear: function () {
        this.chart.clear();
      },
      singleLineChart: function () { //单曲线图(无x轴、y轴)
        var chart = new G2.Chart({
          container: this.ids,
          //forceFit: true,
          width: this.widths,
          height: this.heights,
          padding: [10, 20, 10, 30]
        });
        chart.source(this.datas);
        chart.scale('_value', {
          min: 0
        });
        chart.scale('_year', {
          range: [0, 1]
        });
        chart.tooltip({
          crosshairs: {
            type: 'line'
          }
        });
        chart.axis('_year', false);
        chart.axis('_value', false);
        chart.line().color('_name', this.color).position('_year*_value').shape('smooth');
        chart.render();
        this.chart = chart;
      },
      singleLineWithAxisChart: function () { //单曲线图（有x轴、y轴）
        var chart = new G2.Chart({
          container: this.ids,
          forceFit: true,
          width: this.widths,
          height: this.heights
        });
        chart.source(this.datas);
        chart.scale('value', {
          min: 0
        });
        chart.scale('year', {
          range: [0, 1]
        });
        chart.tooltip({
          crosshairs: {
            type: 'line'
          }
        });
        chart.line().position('year*value').shape('smooth');
        chart.render();
      },
      doubleLineChart: function () { //双曲线图
        var chart = new G2.Chart({
          container: this.ids,
          width: this.widths,
          height: this.heights,
          forceFit: this.widths ? false : true,
          padding: [20, 30, this.legend ? 40 : 70, 50]
        });
        chart.source(this.datas, {
          _date: {
            range: [0, 1],
            tickCount: 15,
          },
          _value: {
            min: this.min ? this.min : 0,
            tickInterval: this.level,
          }
        });
        chart.axis('_date', {
          label: {
            formatter: function formatter(val) {
              var arr = val.split("-");
              if (arr.length == 3) {
                return arr[1] + "/" + arr[2];
              } else if (arr.length == 2) {
                return arr[0] + "/" + arr[1];
              } else {
                return val;
              }
            }
          },
        });
        chart.line().position('_date*_value').color('title').shape('smooth');
        if (this.legend) {
          chart.legend(false);
        }
        chart.render();
        this.chart = chart;
      },
      doubleLinewithrigntaxis: function () {//双曲线图,左右都有y轴

        var chart = this.chart;
        if (chart == null) {
          chart = new G2.Chart({
            container: this.ids,
            forceFit: true,
            width: this.widths,
            height: this.heights,
            padding: [20, 80, 50, 80]
          });
        }

        var scale = {
          _date: {
            range: [0, 1]
          },
          _value: {
            alias: this.hasPro(this.lineAlias,'one') || '药品收入',
            min: 0
          },
          _persent: {
            alias: this.hasPro(this.lineAlias,'two') || '收入占比',
            formatter: function formatter(value) {
              return value + '%';
            },
            tickInterval: 20,
            max: 100,
          },
        };
        var view = chart.view();
        view.source(this.datas, scale);
        view.line().position('_date*_value').color('#1890FF').size(2).shape('smooth');
        view.line().position('_date*_persent').color('#F5C228').size(2).shape('smooth');
        chart.render();

        this.chart = chart;
      },
      areaChart: function () { //面积图
        var chart = new G2.Chart({
          container: this.ids,
          forceFit: true,
          height: window.innerHeight
        });
        chart.source(this.datas);
        chart.scale({
          value: {
            min: 10000
          },
          year: {
            range: [0, 1]
          }
        });
        chart.axis('value', {
          label: {
            formatter: function formatter(val) {
              return (val / 10000).toFixed(1) + 'k';
            }
          }
        });
        chart.tooltip({
          crosshairs: {
            type: 'line'
          }
        });
        chart.area().position('year*value');
        chart.line().position('year*value').size(2);
        chart.render();
      },
      barChart: function () { //柱状图
        var chart = new G2.Chart({
          container: this.ids,
          width: this.widths,
          height: this.heights,
          forceFit: this.widths ? false : true,
          padding: [20, 50, this.legend ? 40 : 70, 50]
        });
        chart.source(this.datas);
        chart.scale('_value', {
          tickInterval: this.level,
        });
        chart.interval().position('_name*_value');
        chart.render();
        this.chart = chart;
      },
      groupChart: function () { //分组柱状图
        var chart = new G2.Chart({
          container: this.ids,
          width: this.widths,
          height: this.heights,
          forceFit: this.widths ? false : true,
          padding: [20, 40,70, 80]
        });
        chart.source(this.datas);
        chart.interval().position('_type*_value').color('_name',["#1890FF","#F5C228"]).adjust([{
          type: 'dodge',
          marginRatio: 0.01
        }]);
        chart.render();
        this.chart = chart;
      },
      groupBarChart: function () {
        var chart = new G2.Chart({
          container: this.ids,
          height: this.heights,
          forceFit: true,
          padding: [0, 20, 70, 90],
        });
        chart.source(this.datas, {
          _value: {
            nice: false,
            alias: '门诊人次'
          }
        });
        chart.tooltip(true, {
          showTitle: false // 默认标题不显示
        });
        chart.axis('_value', false);
        chart.coord().transpose();
        chart.facet('mirror', {
          fields: ['_type'],
          autoSetAxis: false,
          transpose: true,
          showTitle: false,
          padding: [0, 5, 0, 0],
          eachView: function eachView(view, facet) {
            var facetIndex = facet.colIndex;
            if (facetIndex === 0) {
              view.axis('_group', {
                position: 'top',
                label: {
                  textStyle: {
                    fill: '#aaaaaa',
                    fontSize: 12
                  },
                  formatter: function formatter(val) {
                    return val + '岁';
                  }
                },
                tickLine: {
                  alignWithLabel: false,
                  length: 0
                },
                line: {
                  lineWidth: 0
                }
              });
              view.axis('_value', {
                grid: null,
                alias: '门诊人次'
              });
              view.scale('_value', {
                tickInterval: 50,
              });
            } else {
              view.axis('_group', false);
              view.axis('_value', {
                grid: null
              });
              view.scale('_value', {
                tickInterval: 50,
              });
            }
            var color = facetIndex === 0 ? '#1890FF' : '#F5C228';
            view.interval().position('_group*_value').color('_type', color).size(25).opacity(1);
          }
        });
        chart.render();
        this.chart = chart;
      },
      ringChart: function () { //环形图
        // 可以通过调整这个数值控制分割空白处的间距，0-1 之间的数值
        var sliceNumber = 0;

        // 自定义 other 的图形，增加两条线
        G2.Shape.registerShape('interval', 'sliceShape', {
          draw: function draw(cfg, container) {
            var points = cfg.points;
            var path = [];
            path.push(['M', points[0].x, points[0].y]);
            path.push(['L', points[1].x, points[1].y - sliceNumber]);
            path.push(['L', points[2].x, points[2].y - sliceNumber]);
            path.push(['L', points[3].x, points[3].y]);
            path.push('Z');
            path = this.parsePath(path);
            return container.addShape('path', {
              attrs: {
                fill: cfg.color,
                path: path
              }
            });
          }
        });

        var chart = this.chart;
        if (chart == null) {
          chart = new G2.Chart({
            container: this.ids,
            width: this.widths,
            height: this.heights,
            forceFit: this.widths ? false : true,
            padding: this.padding || [20, 20, 70, 20]
          });
        }

        chart.source(this.datas);
        chart.coord('theta', {
          innerRadius: 0.75
        });

        var gStyle = this.totalStyle;
        var bgView = chart.view();

        var htmlStr = ` <div><div class="g2-guide-html"
                                  style="
                                  color:${this.hasPro(gStyle, 'fill') || '#262626'};
                                  line-height: ${this.hasPro(gStyle, 'lineHeight') || '14px'};
                                  font-size: ${this.hasPro(gStyle, 'fontSize') || '20px'};
                                  text-align: ${this.hasPro(gStyle, 'textAlign') || 'center'};
                                  font-weight: ${this.hasPro(gStyle, 'fontWeight') || 'bold'};
                                  display: flex;
                                  align-items: center;
                                  justify-content:center;
                                  width: ${this.hasPro(gStyle, 'width') || '100%'};
                                  ">
                             <span>${this.totals}</span>
                        </div></div> `;


        bgView.guide().html({
          position: ['50%', '50%'],
          html: htmlStr
        });

        if (this.noLeg) {
          chart.legend(false);
        }

        chart.tooltip({
          showTitle: false
        });
        chart.intervalStack().position('_value').color('_type').shape('sliceShape');
        chart.render();
        this.chart = chart;
      },

      dashboardchart: function () { //仪表盘
        var Shape = G2.Shape;
        // 自定义Shape 部分
        Shape.registerShape('point', 'pointer', {
          drawShape: function drawShape(cfg, group) {
            var center = this.parsePoint({ // 获取极坐标系下画布中心点
              x: 0,
              y: 0
            });
            // 绘制指针
            group.addShape('line', {
              attrs: {
                x1: center.x,
                y1: center.y,
                x2: cfg.x,
                y2: cfg.y,
                stroke: cfg.color,
                lineWidth: 3,
                lineCap: 'round'
              }
            });
            return group.addShape('circle', {
              attrs: {
                x: center.x,
                y: center.y,
                r: 5.75,
                stroke: cfg.color,
                lineWidth: 3.5,
                fill: '#fff'
              }
            });
          }
        });

        var data = [];

        var chart = this.chart;
        if (chart == null) {
          chart = new G2.Chart({
            container: this.ids,
            width: this.widths,
            forceFit: this.widths ? false : true,
            height: this.heights,
            padding: [10, 10, 10, 10],  // 上，右，下，左
          });
        }

        data.push(this.datas);
        chart.source(data);

        chart.coord('polar', {
          startAngle: -9 / 8 * Math.PI,
          endAngle: 1 / 8 * Math.PI,
          radius: 0.75
        });
        chart.scale('value', {
          min: 0,
          max: this.max ? this.max : 9,
          tickInterval: this.level ? this.level : 1,
          nice: false
        });

        chart.axis('1', false);
        chart.axis('value', {
          zIndex: 2,
          line: null,
          label: {
            offset: this.offset ? this.offset : -11,
            textStyle: {
              fontSize: 14,
              textAlign: 'center',
              textBaseline: 'middle',
              fontWeight: 'normal',
              fill: "#AFAFAF"
            }
          },
          subTickCount: 4,
          subTickLine: {
            length: -8,
            stroke: '#fff',
            strokeOpacity: 1
          },
          tickLine: {
            length: -17,
            stroke: '#fff',
            strokeOpacity: 1
          },
          grid: null
        });
        chart.legend(false);
        chart.point().position('value*1').shape('pointer').color('#3C90F7').active(false);

        // 绘制仪表盘背景
        chart.guide().arc({
          zIndex: 0,
          top: false,
          start: [0, 0.945],
          end: [this.max ? this.max : 9, 0.945],
          style: { // 底灰色
            stroke: '#EFEEEE',
            lineWidth: this.lineWidth ? this.lineWidth : 14
          }
        });
        // 绘制指标
        chart.guide().arc({
          zIndex: 1,
          start: [0, 0.945],
          end: [data[0].value, 0.945],
          style: {
            stroke: '#3C90F7',
            lineWidth: this.lineWidth ? this.lineWidth : 14
          }
        });

        // 绘制指标数字
        chart.guide().html({
          position: ['50%', '100%'],
          html: '<div style="width: 300px;text-align: center">' + '<p style="font-size: 13px; color:' + data[0].color1 + ';margin-top: 10px;">' + data[0].label1 + '</p>' + '<p style="font-size: 14px;color: ' + data[0].color2 + ';margin-top: -15px;">' + data[0].label2 + '</p>' + '</div>'
        });
        chart.render();

        this.chart = chart;
      },

      stackedBarChart() {

        var data = this.datas || [];

        var chart = this.chart;
        if (chart == null) {
          chart = new G2.Chart({
            container: this.ids,
            width: this.widths,
            forceFit: this.widths ? false : true,
            height: this.heights,
            padding: [10, 0, 39, 0]

          });
        }

        chart.source(data);
        chart.axis('_title', false);
        chart.axis('_value', false);
        chart.axis('_name', false);

        chart.legend({
          // offset:-10,
          position: 'bottom',
          marker: 'circle' // 设置图例 marker 的显示样式
        });
        chart.coord().transpose();
        chart.intervalStack().position('_title*_value')
          .color('_name', ['#1890ff', '#ebb83f', '#6bbdcd', '#e18438', '#d83922'])
          .size(12).opacity(1)
          .tooltip('_name*_value*_unit', (b, c, d) => {
            return {
              name: b,
              value: c + "例"
            };
          })

        chart.render();

        this.chart = chart;
      },

      hasPro(obj, pro) {

        if (obj == null)
          return false

        if (obj.hasOwnProperty(pro))
          return obj[pro];

        return false;
      }
    }
  }
</script>


